<?php

/*
    HTMLTableHelper class
    
        Author:     Alfredo Mungo
        License:    LGPL
        Copyright:  2012
*/

class HTMLTableHelper {

    private $colnames;
    private $rows;
    private $attr;
    
    /*
        Creates a new instance of this class.
        
        Arguments:
            array[string] $col_names: An array of column names represented by strings.
            array[string] $attr: An associative array of attributes in which the key is the attribute name, and the value the attribute content.
            
        Throw:
            WrongTypeException
    */
    function __construct($col_names, $attr = null) {
    
        if(is_array($col_names))
            $this->colnames =  $col_names;
        else
            throw new WrongTypeException();
        
        if(is_array($attr))
            $this->attr = $attr;
        elseif($attr !== null)
            throw new WrongTypeException();
        
        $this->rows = array();
        
    }
    
    
    /*
        Generate the HTML output.
        
        Arguments:
            bool $echo: if true, the HTML is directly sent to stdout; if false, the HTML output is returned by the method.
    */
    function getHTML($echo = false) {
        $code = '<table';
        
        if($this->attr != null) // Table attributes
            foreach($this->attr as $k => $v)
                $code .= " $k=\"$v\"";
        
        $code .= ">";
        
        if($this->colnames != null) { // Heading
            $code .= '<thead><tr>';
            
            foreach($this->colnames as $v)
                $code .= "<th>$v";
            
            $code .= '<tbody>';
        }
        
        // Table data
        foreach($this->rows as $v) {
            $code .= '<tr>';
            
            foreach($v as $w)
                $code .= "<td>$w";
        }
        
        $code .= '</table>';
        
        // Output
        if($echo)
            echo $code;
        else
            return $code;
    }
    
    /*
        Append a row of data to the end of the table.
        
        Arguments:
            array[string] $row: An array
    */
    function append($row) {
        $this->rows[] = $row;
    }

};

?>